package com.iceberg;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;

public class AlgorithmVisualizer {

    // TODO: 创建自己的数据
    private int DELAY = 1;
    private static int blockSize = 8;
    private static final int d[][] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    private MazeData data;        // 数据
    private AlgorithmFrame frame;    // 视图

    public AlgorithmVisualizer(String fileName){

        // 初始化数据
        // TODO: 初始化数据
        data = new MazeData(fileName);
        int sceneHeight = data.N() * blockSize;
        int sceneWidth = data.M() * blockSize;
        // 初始化视图
        EventQueue.invokeLater(() -> {
            frame = new AlgorithmFrame("Welcome", sceneWidth, sceneHeight);
            new Thread(() -> {
                run();
            }).start();
        });
    }

    // 动画逻辑
    private void run(){
        setData(-1, -1, true);
        if (!go(data.getEntranceX(), data.getEntranceY())){
            System.out.println("Maze has no solution");
        }
        setData(-1, -1, true);
    }

    private boolean go(int x, int y){

        if (!data.inArea(x, y)){
            throw new IllegalArgumentException("Maze Boundary Exception");
        }
        data.visited[x][y] = true;
        setData(x, y, true);
        if (x == data.getExitX() && y == data.getExitY()){
            System.out.println("find solution");
            return true;
        }
        for (int i = 0; i < 4; i ++){
            int newX = x + d[i][0];
            int newY = y + d[i][1];
            if (data.inArea(newX, newY)
                    && data.getData(newX, newY) == MazeData.ROAD
                    && !data.visited[newX][newY]){
                if (go(newX, newY)){
                    return true;
                }
            }
        }
        setData(x, y, false);
        return false;
    }

    private void setData(int x, int y, boolean isPath){
        if (data.inArea(x, y)){
            data.path[x][y] = isPath;
        }
        frame.render(data);
        AlgorithmVisHelper.pause(DELAY);
    }

    public static void main(String[] args) {
        // TODO: 根据需要设置其他参数，初始化visualizer
        AlgorithmVisualizer visualizer = new AlgorithmVisualizer("D:/VVader/GIT/DataStructureAlgorithms/Maze/src/com/iceberg/maze_101_101.txt");
    }
}
